package web.study.freemarker;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FirstFreemarkerServlet extends HttpServlet
{
    
    /**
     * 序列化
     */
    private static final long serialVersionUID = 1L;
    
    Configuration cfg;
    
    @Override
    public void init()
        throws ServletException
    {
        cfg = new Configuration();
        cfg.setServletContextForTemplateLoading(getServletContext(), "WEB-INF/templates");
    }
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
    {
        Map<String, String> root = new HashMap<String, String>();
        root.put("message", "hello world");
        Template t = cfg.getTemplate("test.ftl");
        PrintWriter out = resp.getWriter();
        try
        {
            //看到了吧？用模板来开发servlet可以让我们用一句代码代替一堆代码。
            t.process(root, out);
        }
        catch (TemplateException e)
        {
            e.printStackTrace();
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
    {
        doGet(req, resp);
    }
}
